#!/bin/sh
#
#  SUSAN® - Sole of Unix Save ANything
#
# Copyright (C) 2015-2016 Skyatlas Co. CN
# Copyright (C) 2015-2016 Hechzh Property
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of version three of the GNU Affero General Public
# License as published by the Free Software Foundation and included
# in the file LICENSE.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
set -a

#
# Source the Susan config functions.
#
. @scriptdir@/susan-config-lib.sh

GLUSTERFIND="glusterfind"
BACKUP_LEVEL="Full"
SINCE_TIME="0"
JOB_TYPE="Backup"

usage()
{
   echo "Usage: $0 [-h] [-l <level>] [-s <since_time>] [-t <jobtype>] <action> <arguments...>"
}

pre_backup()
{
   if [ $# -lt 2 ]; then
      echo "pre_backup action needs 2 arguments"
      exit 1
   fi

   #
   # $1 - volumename
   # $2 - outputfile
   #
   case ${BACKUP_LEVEL} in
      Full)
         ${GLUSTERFIND} query $1 $2 --since-time ${SINCE_TIME} --full
         ;;
      Incremental|Differential)
         ${GLUSTERFIND} query $1 $2 --since-time ${SINCE_TIME}
         ;;
      *)
         ;;
   esac
}

post_backup()
{
   if [ $# -lt 2 ]; then
      echo "post_backup action needs 2 arguments"
      exit 1
   fi

   #
   # $1 - volumename
   # $2 - outputfile
   #
   rm -f $2
}

main()
{
   #
   # Parse options.
   #
   while getopts "hl:s:t:" arg
   do
      case ${arg} in
         h|\?)
            usage
            exit 0
            ;;
         l)
            BACKUP_LEVEL="${OPTARG}"
            ;;
         s)
            SINCE_TIME="${OPTARG}"
            ;;
         t)
            JOB_TYPE="${OPTARG}"
            ;;
         *)
            usage
            exit 1
            ;;
      esac
   done
   nr_shift=`expr $OPTIND - 1`
   shift ${nr_shift}

   if [ $# -lt 1 ]; then
      usage
      exit 1
   fi

   action=$1
   shift

   case ${action} in
      prebackup)
         pre_backup $*
         ;;
      postbackup)
         post_backup $*
         ;;
      *)
         echo "Unknown action ${action}, aborting ..."
         exit 1
         ;;
   esac

   exit 0
}

main $*
